// 获取主题详情
export async function fetchTopicDetail(id) {
    const response = await fetch(
        `https://cnodejs.org/api/v1/topic/${id}`
    );
    const data = await response.json();
    if (data.success) {
        return data.data;
    } else {
        throw new Error(data);
    }
}

// 获取主题列表
export async function fetchTopics({
    page = 1,
    tab = '', // 'ask' | 'share' | 'job' | 'good'
    limit = 10,
}) {
    const response = await fetch(
        `https://cnodejs.org/api/v1/topics?limit=${limit}&page=${page}&tab=${tab}`
    );
    const data = await response.json();
    if (data.success) {
        return data.data;
    } else {
        throw new Error(data);
    }
}

// 获取带评论的主题列表的前10个数据
export async function fetchTopicsWithCommentTop10() {

    const top10List = await fetchTopics({
        limit: 10,
    });
    const promiseList = top10List.map(
        item => fetchTopicDetail(item.id)
            .then((data) => {
                const newCommentList = data.replies
                    .sort(
                        (a, b) => b.ups.length - a.ups.length
                    )
                    .slice(0, 3);
                return {
                    ...data,
                    replies: newCommentList,
                };
            })
    );
    const detailList = await Promise.all(promiseList);
    return detailList;
}